#! /usr/bin/env python
# -*- coding: utf-8 -*-

# *************************************************************
#  Copyright (c) Huoty - All rights reserved
#
#      Author: Huoty <sudohuoty@gmail.com>
#  CreateTime: 2016-09-30 13:59:52
# *************************************************************

"""日志系统"""

import os
import logging
from logging.handlers import SMTPHandler


class CustomSMTPHandler(SMTPHandler):
    def emit(self, record):
        # add extra record
        record.host = __import__("socket").gethostname()
        super(CustomSMTPHandler, self).emit(record)

    def getSubject(self, record):
        formatter = logging.Formatter(fmt=self.subject)
        return formatter.format(record)


error_mail_template = '''\
Logger Name:        %(name)s
Message type:       %(levelname)s
Location:           %(pathname)s:%(lineno)d
Module:             %(module)s
Function:           %(funcName)s
Host:               %(host)s
Time:               %(asctime)s

Message:

%(message)s
'''

error_mail_config = {
    "mailhost": 'smtp.yeah.net',
    "fromaddr": os.environ["MAIL_ADDR"],
    "toaddrs": ('loveqing2013@foxmail.com',),
    "subject": '%(name)s Error: %(message)s',
    "credentials": (os.environ["MAIL_ADDR"], os.environ["MAIL_PASS"]),
}

def get_logger(name, log_format=None, error_mail_format=None):
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)

    # add main log handler for error
    mail_handler = CustomSMTPHandler(**error_mail_config)
    mail_handler.setLevel(logging.ERROR)
    mail_handler.setFormatter(logging.Formatter(
        error_mail_format if error_mail_format else error_mail_template
    ))
    logger.addHandler(mail_handler)

    # add stream log handler for info
    stdout_handler = logging.StreamHandler(sys.stdout)
    stdout_handler.setLevel(logging.DEBUG)
    stdout_handler.setFormatter(logging.Formatter(
        log_format if log_format else '[%(levelname)s %(asctime)s %(name)s] %(message)s'
    ))
    logger.addHandler(stdout_handler)

    return logger

def get_tornado_app_log(error_mail_format=None):
    from tornado.log import app_log
    mail_handler = CustomSMTPHandler(**error_mail_config)
    mail_handler.setLevel(logging.ERROR)
    mail_handler.setFormatter(logging.Formatter(
        error_mail_format if error_mail_format else error_mail_template
    ))
    app_log.addHandler(mail_handler)
    return app_log


# Script starts from here

if __name__ == "__main__":
    pass
